package dst.ass3.aop.impl;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DirectoryScanner {

    private Map<String, File> jarFileMap = Collections.synchronizedMap(new HashMap<String, File>());
    private PluginExecutor pluginExecutor;

    public DirectoryScanner(PluginExecutor pluginExecutor) {
        this.pluginExecutor = pluginExecutor;  //used to call the jar method
    }

    /**
     * Go through all the given directories and Search for .jar Files
     * @param directories
     */
    public synchronized void scanDirectories(Set<File> directories) {
    	
    	//Go through all dir pathes
        for (File dir : directories) {
            File files[] = dir.listFiles();
            
            for (File file : files) {
            	if(file.getName().endsWith(".jar")){  //just look at jar files
	                try {
	                    String filename = file.getCanonicalPath();	//getName
	                    File saved = jarFileMap.get(filename);			//get File from jarsList
	
	                    if (saved != null && saved.lastModified() >= file.lastModified()) { //look if it is eventually replaced
	                        continue;  //the saved jar is younger than the scanned
	                    }
	
	                    jarFileMap.put(filename, file); //add this file to Map
	                    
	                    pluginExecutor.onNewJar(file);
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
            	}
            }
        }
    }

}


